package com.dpwgc.demo.utils;

import com.dpwgc.demo.config.TencentCosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;

/**
 * 文件上传工具类-腾讯对象存储
 */
@Component
public class UploadUtil {

    @Autowired
    TencentCosConfig tencentCosConfig;

    @Autowired
    DateUtil dateUtil;


    /**
     * 文件上传
     * @param file  文件流
     * @param type  文件类型
     * @param session
     * @return
     */
    public ResultUtil<Object> uploadFileUtil(MultipartFile file, String type, HttpSession session){
        ResultUtil<Object> result = new ResultUtil<>();
        HashMap<String,String> uploadInfo = new HashMap<>();

        if (file==null){
            result.setCode(100);
            result.setMsg("文件内容为空");
            return result;
        }

        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = type + "_" + UUID.randomUUID() +  eName;
        Calendar cal = Calendar.getInstance();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DATE);

        // 初始化对象存储用户
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getAccessKey(), tencentCosConfig.getSecretKey());
        // 设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCosConfig.getBucket()));
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        String bucketName = tencentCosConfig.getBucketName();


        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp",null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/dpwgc_im/"+type+"/"+year+"/"+month+"/"+day+"/"+newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);


            uploadInfo.put("url",tencentCosConfig.getCdnurl() + putObjectRequest.getKey());
            result.setCode(200);
            result.setData(uploadInfo);
            result.setMsg("上传成功");
            return result;

        } catch (IOException e) {
            uploadInfo.put("err",e.toString());
            result.setCode(100);
            result.setData(uploadInfo);
            result.setMsg("上传失败");
            return result;
        }finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }

    }

    /**
     * 文件上传(自定义文件名与文件路径)
     * @param file  文件流
     * @param type  文件类型
     * @param session
     * @return
     */
    public ResultUtil<Object> uploadFileFreeUtil(MultipartFile file, String type, String fileName, String url, HttpSession session){
        ResultUtil<Object> result = new ResultUtil<>();
        HashMap<String,String> uploadInfo = new HashMap<>();

        if (file==null){
            result.setCode(100);
            result.setMsg("文件内容为空");
            return result;
        }

        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = fileName +  eName;
        Calendar cal = Calendar.getInstance();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DATE);

        // 初始化对象存储用户
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getAccessKey(), tencentCosConfig.getSecretKey());
        // 设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCosConfig.getBucket()));
        // 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        String bucketName = tencentCosConfig.getBucketName();


        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp",null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/"+type+"/"+url+"/"+newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);


            uploadInfo.put("url",tencentCosConfig.getCdnurl() + putObjectRequest.getKey());
            result.setCode(200);
            result.setData(uploadInfo);
            result.setMsg("上传成功");
            return result;

        } catch (IOException e) {
            uploadInfo.put("err",e.toString());
            result.setCode(100);
            result.setData(uploadInfo);
            result.setMsg("上传失败");
            return result;
        }finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }

    }
}
